﻿using System;
using System.Runtime.CompilerServices;
using UnityEngine;

public static class TextureExtension
{
    public static Texture2D ForceInstantiate(this Texture2D texture)
    {
        RenderTexture dest = RenderTexture.GetTemporary(texture.width, texture.height, 0, RenderTextureFormat.Default, RenderTextureReadWrite.Linear);
        Graphics.Blit(texture, dest);
        RenderTexture active = RenderTexture.active;
        RenderTexture.active = dest;
        Texture2D textured = new Texture2D(texture.width, texture.height);
        textured.ReadPixels(new Rect(0f, 0f, (float) dest.width, (float) dest.height), 0, 0);
        textured.Apply();
        RenderTexture.active = active;
        RenderTexture.ReleaseTemporary(dest);
        return textured;
    }

    public static void SetPixels(this Texture2D tex, Color color)
    {
        Color[] colors = new Color[tex.width * tex.height];
        for (int i = 0; i < colors.Length; i++)
        {
            colors[i] = color;
        }
        tex.SetPixels(colors);
    }
}

